/**
 * Created by admin on 2016/8/19.
 */
var assert = require('../assert');

exports.handler = function (req, res) {
    var shareTpye = req.params.shareType;
    if (shareTpye == "coupon") {
        couponResponse(req, res);
    }
};

exports.postCoupon = function (req, res) {
    //  获取参数
    var mobile = req.body.mobile;
    var couponId = req.body.couponId;
    var couponType = req.body.couponType;
    // 检查参数是否有空值
    var hasNull = assert.check_parms([mobile, couponId]);
    if (hasNull) {
        res.send(assert.response_sms(400, '参数不能为空'));
        return
    }
    // 判断手机号的格式是否合法
    if (mobile.length != 11) {
        res.send(assert.response_sms(400, '手机号长度错误'));
        return
    }
    // 正则判断
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})||(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    if (!myreg.test(mobile)) {
        res.send(assert.response_sms(400, '请填入有效的手机格式'));
        return
    }
    // 获取用户
    function getUser(mobile) {
        return new Promise(function (resolve, reject) {
            var query = new Parse.Query('User');
            query.equalTo('mobile', mobile);
            query.first().then(function (user) {
                resolve(user);
            }, function (error) {
                reject(error);
            })
        })
    }

    // 获取优惠券模板
    function getCouponTemplate(couponId) {
        return new Promise(function (resolve, reject) {
            var coupon_query = new Parse.Query('PYCoupon');
            coupon_query.equalTo('redeemCode', couponId);
            coupon_query.first().then(function (coupon) {
                if(coupon){
                    var couponTemplate_query = new Parse.Query('PYCouponTemplate');
                    couponTemplate_query.get(coupon.get('couponTemplate').id).then(function (couponTemplate) {
                        resolve({coupon: coupon, template: couponTemplate})
                    }, function (error) {
                        reject(error);
                    });
                }else{
                    reject("获取验证码失败");
                }

            })
        })
    }

    // 新建用户
    function createUser(mobile) {
        return new Promise(function (resolve, reject) {
            var user = new Parse.User();
            var password = Math.floor(Math.random() * 900000 + 100000);
            user.set('mobile', mobile);
            user.set('username', mobile);
            user.set('password', toString(password));
            user.signUp().then(function (result) {
                resolve(result);
                // 发送消息给用户，发送mobile和password
                send_sms(mobile, password, 2);
                // 此处需要改
            }, function (error) {
                reject(error);
                console.log('用户生成失败' + error.message)
            });
        });
    }

    // 查询此优惠券是否已经被领取
    var log_query = new Parse.Query('PYCouponGetLog');
    log_query.equalTo('mobile', mobile);
    log_query.equalTo('tag', couponType);
    log_query.first().then(function (couponLog) {
        if (couponLog) {
            //表示已经领取过了,但是还是返回200,然后返回用户的ID
            getUser(mobile).then(function (resultsUser) {
                res.send(assert.response_sms(302, '该手机号已经领取过该类型红包', {userId: resultsUser.id, couponId:couponLog.get('couponCode')}));
            }, function (err) {
                res.send(assert.response_sms(201, '查询领取记录失败'));
            })
        } else {
            //红包和手机号可行,则进行领取逻辑
            Promise.all([getUser(mobile), getCouponTemplate(couponId)]).then(function (results) {
                var user = results[0];
                var couponTemplate = results[1].template;
                var coupon = results[1].coupon;
                userCoupon = coupon.get('user');
                if(userCoupon){
                    //表示这个红包已经被领取了,返回错误
                    res.send(assert.response_sms(303, '优惠码已被兑换'));
                    return;
                }
                if (user) {

                    coupon.set('user', user);
                    coupon.save().then(function (result) {
                        //优惠券领取成功
                        res.send(assert.response_sms(200, '优惠券领取成功', {userId: user.id, couponId:couponId}));
                        //领取记录里插入数据
                        insertGetLog(mobile, couponId,couponType, result.get('user'), result);
                        //发短信
                        send_sms(mobile, couponTemplate.get('worth'), 1);
                    }, function (error) {
                        //优惠券领取失败
                        res.send(assert.response_sms(400, '优惠券领取失败'));
                    });
                } else {
                    createUser(mobile).then(function (user) {
                        coupon.set('user', user);
                        coupon.save().then(function (result) {
                            //优惠券领取成功
                            res.send(assert.response_sms(200, '优惠券领取成功', {userId: user.id,couponId:couponId}));
                            //领取记录里插入数据
                            insertGetLog(mobile, couponId,couponType, result.get('user'), result);
                            //发短信
                            send_sms(mobile, couponTemplate.get('worth'), 1);
                        }, function (error) {
                            //优惠券领取失败
                            res.send(assert.response_sms(400, '优惠券领取失败'));
                            console.log(error.message);
                        });
                    }, function (error) {
                        console.log('创建对象出错', error);
                        res.send(assert.response_sms(401,"保存领取信息错误"));
                    });
                }
            }, function (error) {
                console.log(error);
                res.send(assert.response_sms(500,"该优惠码无效"));
            });
        }
    }, function (err) {
        res.send(assert.response_sms(501,"查询领取记录失败"));
    });
};

// 返回用户的红包列表
exports.getCoupons = function (req, res) {
    var userId = req.query.userId;
    if (!userId) {
        res.send(assert.response_sms(400, 'userId为空'));
    }
    // 新建用户
    var user = new Parse.User();
    user.id = userId;
    var query = new Parse.Query('PYCoupon');
    query.include('couponTemplate');
    query.equalTo('user', user);
    // 查找用户的coupon
    query.find().then(function (coupons) {
        // 格式化返回字段
        var response_content = [];
        for (var i = 0; i < coupons.length; i++) {
            var temp = {};
            temp = assert.obj2dicCoupon(coupons[i].get('couponTemplate'), ['worth', 'validityEnd', 'validityBegin', 'limitPrice','channel','from']);
            temp['redeemCode'] = coupons[i].get('redeemCode');
            temp['lastValidityEnd'] = coupons[i].get('couponTemplate').get('validityEnd');
            if (coupons[i].get('usePharmacy')) {
                temp['usePharmacy'] = true
            }
            response_content.push(temp);
        }
        res.send(assert.response_sms(200, '获取优惠券列表成功', response_content));
    }, function (error) {
        res.send(assert.response_sms(400, '获取优惠券列表失败'));
        console.log(error);
    });

};
// 返回红包详情
exports.getCouponTemplate = function (req, res) {
    var couponId = req.params.couponId;
    if (!couponId) {
        res.send(assert.response_sms(400, 'couponId为空'));
        return
    }
    var Coupon = Parse.Object.extend('PYCoupon');
    var coupon = new Coupon();
    coupon.id = couponId;
    var log_query = new Parse.Query('PYCouponGetLog');
    log_query.equalTo('coupon', coupon);
    log_query.find().then(function (coupons) {
        if (coupons.length > 0) {
            res.send(assert.response_sms(201, '该红包已经被领取了'));
        }
    }, function (error) {
        res.send(assert.response_sms(400, '查询红包出错'));
        console.log(error);
    });
    // 穿件查询对象
    var query = new Parse.Query('PYCoupon');
    query.include('couponTemplate');
    query.get(couponId).then(function (coupon) {
        // 格式化返回的格式
        var couponTemplate = coupon.get('couponTemplate');
        var response_content = assert.obj2dicCoupon(couponTemplate, ['validityEnd', 'intro', 'limitPrice', 'worth', 'type']);
        res.send(assert.response_sms(200, '返回红包成功', response_content));
    }, function (error) {
        res.send(assert.response_sms(400, '返回红包失败'));
        console.log(error.message);
    });
};

function couponResponse(req, res) {
    //获取店铺ID和红包模板ID
    var pid = req.query.pid;
    var tid = req.query.tid;
    console.log(pid, tid);
    var query = new Parse.Query("PYCouponTemplate");
    query.get(tid).then(function (pyCouponTemplate) {
        if (pyCouponTemplate) {
            var content = {};
            content['couponWorth'] = pyCouponTemplate.get("worth");
            content['limitPrice'] = pyCouponTemplate.get('limitPrice');
            content['validityEnd'] = pyCouponTemplate.get('validityEnd');
            content['worth'] = pyCouponTemplate.get('worth');
            var template = swig.compileFile('./public/index.html');
            var output = template(content);
            res.send(output);
        }
    }, function (error) {
        console.log(error)
    });
}
// 1:发送红包 2:发送用户密码
function send_sms(u_mobile, data, type) {
    var content = {};
    content['mobile'] = u_mobile;
    if (type == 1) {
        content['send_type'] = "couponGet";
        content['couponWorth'] = data;
    } else if (type == 2) {
        content['send_type'] = "mobileAutoSign";
        content['password'] = data;
    }
    Parse.Cloud.run("sendSMS", content);
}
// 插入获取红包日志
function insertGetLog(mobile, couponId,tag, user, coupon) {
    var CouponGetLog = Parse.Object.extend('PYCouponGetLog');
    var couponGetLog = new CouponGetLog();
    couponGetLog.set('mobile', mobile);
    couponGetLog.set('user', user);
    couponGetLog.set('tag', tag);
    couponGetLog.set('coupon', coupon);
    couponGetLog.set('couponCode', couponId);
    couponGetLog.save().then(function (result) {
        console.log('插入记录成功', result);
    }, function (error) {
        console.log('插入优惠券失败' + error.message);
    })
}